package pecas.pecasclient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Properties;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader.TileMode;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
 
public class HomeActivity extends Activity {
	// begin socket
	
	private final int START = 0xffffff;
	private final int msgBoxHint = START;
	private final int appendText = START + 1;
	private static final int UDP_SERVER_PORT = 9050;
	private static String UDP_SERVER_IP = "192.168.56.1";
	private static final int MAX_UDP_DATAGRAM_LEN = 1024;

	public static final int FINISHED_RECEIVER = 0;

	DatagramSocket udpReceiver = null;

	Boolean isconnect = false;
	// end socket
	
	// load Image
	
	private static int RESULT_LOAD_IMAGE = 1;
	
	// end image
	String picturePath,picture1,picture2,picture3,picture4,picture5,picture6;
	Properties prop;
	private AssetsPropertyReader assetsPropertyReader;
	private Context context;
	
	TextView chuchay;
	int nguoi = 0;
	ImageView Nguoi1,Nguoi2,Nguoi3,Nguoi4,Nguoi5,Nguoi6;
	ImageView ImageA1,ImageA2,ImageA3,ImageA4,ImageA5,ImageA6,ImageA7,ImageA8,ImageA9,ImageA10;
	ImageView ImageB1,ImageB2,ImageB3,ImageB4,ImageB5,ImageB6,ImageB7,ImageB8,ImageB9,ImageB10;
	ImageView C1;
	ImageView D1,D2,D3,D4,D5,D6,D7,D8,D9,D10,E3;
	TextView A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,F2,F3;
	EditText Gopytext,E1,F1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //if (android.os.Build.VERSION.SDK_INT > 9) {
		  //    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		  //    StrictMode.setThreadPolicy(policy);
	    //}
        
        setContentView(R.layout.activity_home);
        
        GetValue();        
        
        SetGiaiDoan(GetConfig("SoGiaiDoan"));
        UDP_SERVER_IP = GetConfig("IpServer");
		//SetConfig("IpServer","192.168.1.201");
		//Log.i("Duong", "Connet socket " + GetConfig("IpServer"));
		//new LongOperation().execute("1");
		//Log.i("Duong", "Connet socket " + GetConfig("IpServer"));
		//SetValue("","A","1","");
		chuchay.setVisibility(android.view.View.VISIBLE);
    	Gopytext.setVisibility(android.view.View.INVISIBLE);
    	//Log.i("Duong", "End creteon" );    	
    	SetEnable(false);
		// Chon Anh
		Nguoi1.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
            	nguoi = 1;
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
		Nguoi2.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
            	nguoi = 2;
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
		Nguoi3.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
            	nguoi = 3;
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
		Nguoi4.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
            	nguoi = 4;
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
		Nguoi5.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
            	nguoi = 5;
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
		Nguoi6.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
            	nguoi = 6;
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    
		
    }
    
   // load image
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            //Log.v("Duong", namefile);
            if(nguoi == 1)
            {
            	Nguoi1.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture1 = f.getName();
            }
            if(nguoi == 2)
            {
            	Nguoi2.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture2 = f.getName();
            }
            if(nguoi == 3)
            {
            	Nguoi3.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture3 = f.getName();
            }
            if(nguoi == 4)
            {
            	Nguoi4.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture4 = f.getName();
            }
            if(nguoi == 5)
            {
            	Nguoi5.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture5 = f.getName();
            }
            if(nguoi == 6)
            {
            	Nguoi6.setImageBitmap(DrawCircle());
            	File f = new File(picturePath);
                picture6 = f.getName();
            }
            cursor.close();
        }
     
     
    }
    
    // Ve anh thanh hinh tron
    private Bitmap DrawCircle() {
		Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
        Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

        BitmapShader shader = new BitmapShader (bitmap,  TileMode.CLAMP, TileMode.CLAMP);
        Paint paint = new Paint();
        paint.setShader(shader);

        Canvas c = new Canvas(circleBitmap);
        c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);
		return circleBitmap;
	}
    
    // set giai doan
	private void SetGiaiDoan(String SoGiaiDoan) {
		Log.i("Duong", SoGiaiDoan);	
		int gdoan = Integer.valueOf(SoGiaiDoan).intValue();
		if(gdoan == 10)
		{
			Log.i("Duong", SoGiaiDoan);
			setVisible(R.id.Muctieu0, true);
			setVisible(R.id.Muctieu1, true);
			setVisible(R.id.Muctieu2, true);
			setVisible(R.id.Muctieu3, true);
			setVisible(R.id.Muctieu4, true);
			setVisible(R.id.Muctieu5, true);
			setVisible(R.id.Muctieu6, true);
			setVisible(R.id.Muctieu7, true);
			setVisible(R.id.Muctieu8, true);
			setVisible(R.id.Muctieu9, true);
			Log.i("Duong", SoGiaiDoan);
		}
		else if(gdoan == 9)
		{
			setVisible(R.id.Muctieu0, true);
			setVisible(R.id.Muctieu1, true);
			setVisible(R.id.Muctieu2, true);
			setVisible(R.id.Muctieu3, true);
			setVisible(R.id.Muctieu4, true);
			setVisible(R.id.Muctieu5, true);
			setVisible(R.id.Muctieu6, true);
			setVisible(R.id.Muctieu7, true);
			setVisible(R.id.Muctieu8, true);
			setVisible(R.id.Muctieu9, false);
		}
		else if(gdoan == 8)
		{	Log.i("Duong", "8");		
			setVisible(R.id.Muctieu0, true);
			setVisible(R.id.Muctieu1, true);
			setVisible(R.id.Muctieu2, true);
			setVisible(R.id.Muctieu3, true);
			setVisible(R.id.Muctieu4, true);
			setVisible(R.id.Muctieu5, true);
			setVisible(R.id.Muctieu6, true);
			setVisible(R.id.Muctieu7, true);
			setVisible(R.id.Muctieu8, false);
			setVisible(R.id.Muctieu9, false);			
		}
		else if(gdoan == 7)
		{Log.i("Duong", "7");
			setVisible(R.id.Muctieu0, true);
			setVisible(R.id.Muctieu1, true);
			setVisible(R.id.Muctieu2, true);
			setVisible(R.id.Muctieu3, true);
			setVisible(R.id.Muctieu4, true);
			setVisible(R.id.Muctieu5, true);
			setVisible(R.id.Muctieu6, true);
			setVisible(R.id.Muctieu7, false);
			setVisible(R.id.Muctieu8, false);
			setVisible(R.id.Muctieu9, false);
		}
		else if(gdoan == 6)
		{
			Log.i("Duong", "6");
			setVisible(R.id.Muctieu0, true);
			setVisible(R.id.Muctieu1, true);
			setVisible(R.id.Muctieu2, true);
			setVisible(R.id.Muctieu3, true);
			setVisible(R.id.Muctieu4, true);
			setVisible(R.id.Muctieu5, true);
			setVisible(R.id.Muctieu6, false);
			setVisible(R.id.Muctieu7, false);
			setVisible(R.id.Muctieu8, false);
			setVisible(R.id.Muctieu9, false);
		}
		else if(gdoan == 5)
		{
			setVisible(R.id.Muctieu0, true);
			setVisible(R.id.Muctieu1, true);
			setVisible(R.id.Muctieu2, true);
			setVisible(R.id.Muctieu3, true);
			setVisible(R.id.Muctieu4, true);
			setVisible(R.id.Muctieu5, false);
			setVisible(R.id.Muctieu6, false);
			setVisible(R.id.Muctieu7, false);
			setVisible(R.id.Muctieu8, false);
			setVisible(R.id.Muctieu9, false);
		}
		else if(gdoan == 4)
		{
			setVisible(R.id.Muctieu0, true);
			setVisible(R.id.Muctieu1, true);
			setVisible(R.id.Muctieu2, true);
			setVisible(R.id.Muctieu3, true);
			setVisible(R.id.Muctieu4, false);
			setVisible(R.id.Muctieu5, false);
			setVisible(R.id.Muctieu6, false);
			setVisible(R.id.Muctieu7, false);
			setVisible(R.id.Muctieu8, false);
			setVisible(R.id.Muctieu9, false);
		}
		else if(gdoan == 3)
		{
			setVisible(R.id.Muctieu0, true);
			setVisible(R.id.Muctieu1, true);
			setVisible(R.id.Muctieu2, true);
			setVisible(R.id.Muctieu3, false);
			setVisible(R.id.Muctieu4, false);
			setVisible(R.id.Muctieu5, false);
			setVisible(R.id.Muctieu6, false);
			setVisible(R.id.Muctieu7, false);
			setVisible(R.id.Muctieu8, false);
			setVisible(R.id.Muctieu9, false);
		}
		else if(gdoan == 2)
		{
			setVisible(R.id.Muctieu0, true);
			setVisible(R.id.Muctieu1, true);
			setVisible(R.id.Muctieu2, false);
			setVisible(R.id.Muctieu3, false);
			setVisible(R.id.Muctieu4, false);
			setVisible(R.id.Muctieu5, false);
			setVisible(R.id.Muctieu6, false);
			setVisible(R.id.Muctieu7, false);
			setVisible(R.id.Muctieu8, false);
			setVisible(R.id.Muctieu9, false);
		}
		else
		{
			setVisible(R.id.Muctieu0, true);
			setVisible(R.id.Muctieu1, false);
			setVisible(R.id.Muctieu2, false);
			setVisible(R.id.Muctieu3, false);
			setVisible(R.id.Muctieu4, false);
			setVisible(R.id.Muctieu5, false);
			setVisible(R.id.Muctieu6, false);
			setVisible(R.id.Muctieu7, false);
			setVisible(R.id.Muctieu8, false);
			setVisible(R.id.Muctieu9, false);
		}
	}

	// get Value giao dien
	private void GetValue() {
		// row A
		A1 = (TextView) findViewById(R.id.Muctieu0);
		ImageA1 = (ImageView) findViewById(R.id.imageButton0);
		A2 = (TextView) findViewById(R.id.Muctieu1);
		ImageA2 = (ImageView) findViewById(R.id.imageButton1);
		A3 = (TextView) findViewById(R.id.Muctieu2);
		ImageA3 = (ImageView) findViewById(R.id.imageButton2);
		A4 = (TextView) findViewById(R.id.Muctieu3);
		ImageA4 = (ImageView) findViewById(R.id.imageButton3);
		A5 = (TextView) findViewById(R.id.Muctieu4);
		ImageA5 = (ImageView) findViewById(R.id.imageButton4);
		A6 = (TextView) findViewById(R.id.Muctieu5);
		ImageA6 = (ImageView) findViewById(R.id.imageButton5);
		A7 = (TextView) findViewById(R.id.Muctieu6);
		ImageA7 = (ImageView) findViewById(R.id.imageButton6);
		A8 = (TextView) findViewById(R.id.Muctieu7);
		ImageA8 = (ImageView) findViewById(R.id.imageButton7);
		A9 = (TextView) findViewById(R.id.Muctieu8);
		ImageA9 = (ImageView) findViewById(R.id.imageButton8);
		A10 = (TextView) findViewById(R.id.Muctieu9);
		ImageA10 = (ImageView) findViewById(R.id.imageButton9);
		
		// Row B		
		ImageB1 = (ImageView) findViewById(R.id.ImgThucTe0);
		ImageB2 = (ImageView) findViewById(R.id.ImgThucTe1);
		ImageB3 = (ImageView) findViewById(R.id.ImgThucTe2);
		ImageB4 = (ImageView) findViewById(R.id.ImgThucTe3);
		ImageB5 = (ImageView) findViewById(R.id.ImgThucTe4);
		ImageB6 = (ImageView) findViewById(R.id.ImgThucTe5);
		ImageB7 = (ImageView) findViewById(R.id.ImgThucTe6);
		ImageB8 = (ImageView) findViewById(R.id.ImgThucTe7);
		ImageB9 = (ImageView) findViewById(R.id.ImgThucTe8);
		ImageB10 = (ImageView) findViewById(R.id.ImgThucTe9);
		
		// Row C
		C1 = (ImageView) findViewById(R.id.ImgTocdo);
		
		// Row D
		D1 = (ImageView) findViewById(R.id.ImgDudoan0);
		D2 = (ImageView) findViewById(R.id.ImgDudoan1);
		D3 = (ImageView) findViewById(R.id.ImgDudoan2);
		D4 = (ImageView) findViewById(R.id.ImgDudoan3);
		D5 = (ImageView) findViewById(R.id.ImgDudoan4);
		D6 = (ImageView) findViewById(R.id.ImgDudoan5);
		D7 = (ImageView) findViewById(R.id.ImgDudoan6);
		D8 = (ImageView) findViewById(R.id.ImgDudoan7);
		D9 = (ImageView) findViewById(R.id.ImgDudoan8);
		D10 = (ImageView) findViewById(R.id.ImgDudoan9);
		
		// row E
		
		E1 = (EditText) findViewById(R.id.txtLuyke1);
		E3 = (ImageView) findViewById(R.id.ImgLuyke3);
		
		// row F
		
		F1 = (EditText) findViewById(R.id.txtMuctieu1);
		F2 = (TextView) findViewById(R.id.tluyke1);
		F3 = (TextView) findViewById(R.id.tLuyke2);
		
		// row G
		Nguoi1 = (ImageView) findViewById(R.id.imgNguoixuatsac1);		
		Nguoi2 = (ImageView) findViewById(R.id.imgNguoixuatsac2);
		Nguoi3 = (ImageView) findViewById(R.id.imgNguoixuatsac3);
		Nguoi4 = (ImageView) findViewById(R.id.imgNguoixuatsac4);
		Nguoi5 = (ImageView) findViewById(R.id.imgNguoixuatsac5);
		Nguoi6 = (ImageView) findViewById(R.id.imgNguoixuatsac6);
		
		
		// Row H
		chuchay = (TextView) findViewById(R.id.shadowtext);
    	Gopytext = (EditText) findViewById(R.id.txtshadowtext);
		
	}

	//Get file config
	private String GetConfig(String Key) {
		
		context = this;
		assetsPropertyReader = new AssetsPropertyReader(context);
		prop = assetsPropertyReader.getProperties("PecasConfig.properties");
		return prop.getProperty(Key);
	}

	// Set file Config
	private void SetConfig(String Key,String Value) {
		AssetManager am = this.getResources().getAssets();
		InputStream isConfig = null;
		try {
			isConfig = am.open("PecasConfig.properties",Context.MODE_PRIVATE);
			prop.load(isConfig);
			prop.setProperty(Key, Value);//This key exists
			prop.store(new FileOutputStream("config.properties"), null);
		} catch (FileNotFoundException e) {
		    e.printStackTrace();
		}catch (IOException e) {
		    e.printStackTrace();
		}		
	}
	
	// An hien giai doan tren giao dien
	private void setVisible(int view, boolean VISIBLE) {
		int t;		
		if (VISIBLE)
			 t = android.view.View.VISIBLE;
		else
			t =  android.view.View.INVISIBLE;		
		if (view == R.id.Muctieu0)
		{
			
			A1.setVisibility(t);			
			ImageA1.setVisibility(t);
			ImageB1.setVisibility(t);
			D1.setVisibility(t);
		}
		else if (view ==  R.id.Muctieu1)
		{
			A2.setVisibility(t);
			ImageA2.setVisibility(t);
			ImageB2.setVisibility(t);
			D2.setVisibility(t);
		}
		else if (view == R.id.Muctieu2)
		{
			A3.setVisibility(t);
			ImageA3.setVisibility(t);
			ImageB3.setVisibility(t);
			D3.setVisibility(t);
		}
		else if (view == R.id.Muctieu3)
		{
			A4.setVisibility(t);
			ImageA4.setVisibility(t);
			ImageB4.setVisibility(t);
			D4.setVisibility(t);
		}
		else if (view == R.id.Muctieu4)
		{
			A5.setVisibility(t);
			ImageA5.setVisibility(t);
			ImageB5.setVisibility(t);
			D5.setVisibility(t);
		}
		else if (view == R.id.Muctieu5)
		{
			A6.setVisibility(t);
			ImageA6.setVisibility(t);
			ImageB6.setVisibility(t);
			D6.setVisibility(t);
		}
		else if (view == R.id.Muctieu6)
		{
			A7.setVisibility(t);
			ImageA7.setVisibility(t);
			ImageB7.setVisibility(t);
			D7.setVisibility(t);
		}
		else if (view == R.id.Muctieu7)
		{
			A8.setVisibility(t);
			ImageA8.setVisibility(t);
			ImageB8.setVisibility(t);
			D8.setVisibility(t);
		}
		else if (view == R.id.Muctieu8)
		{
			A9.setVisibility(t);
			ImageA9.setVisibility(t);
			ImageB9.setVisibility(t);
			D9.setVisibility(t);
		}
		else 
		{
			A10.setVisibility(t);
			ImageA10.setVisibility(t);	
			ImageB10.setVisibility(t);	
			D10.setVisibility(t);
		}
	}
	
	// Set Gia Tri
	private void setText(String view, String content) {
		
		if(view.compareTo("11") ==0)
			A1.setText(content);
		else if(view.compareTo("12") ==0)
			A2.setText(content);
		else if(view.compareTo("13") ==0)
			A3.setText(content);
		else if(view.compareTo("14") ==0)
			A4.setText(content);
		else if(view.compareTo("15") ==0)
			A5.setText(content);
		else if(view.compareTo("16") ==0)
			A6.setText(content);
		else if(view.compareTo("17") ==0)
			A7.setText(content);
		else if(view.compareTo("18") ==0)
			A8.setText(content);
		else if(view.compareTo("19") ==0)
			A9.setText(content);
		else if(view.compareTo("110") ==0)
			A10.setText(content);
		else if(view.compareTo("21") ==0)
			ImageB1.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("22") ==0)		{			
			ImageB2.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));		}
		else if(view.compareTo("23") ==0)
			ImageB3.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("24") ==0)
			ImageB4.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("25") ==0)
			ImageB5.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("26") ==0)
			ImageB6.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("27") ==0)
			ImageB7.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("28") ==0)
			ImageB8.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("29") ==0)
			ImageB9.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("210") ==0)
			ImageB10.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("31") ==0)
			C1.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("41") ==0)
			D1.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("42") ==0)		{			
			D2.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));		}
		else if(view.compareTo("43") ==0)
			D3.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("44") ==0)
			D4.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("45") ==0)
			D5.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("46") ==0)
			D6.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("47") ==0)
			D7.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("48") ==0)
			D8.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("49") ==0)
			D9.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
		else if(view.compareTo("410") ==0)
			D10.setImageResource(getResources().getIdentifier(content, "drawable", this.getPackageName()));
	}
	
	
	public void Summit_onClick(View v){
		
		chuchay.setVisibility(android.view.View.VISIBLE);
    	Gopytext.setVisibility(android.view.View.INVISIBLE);
    	//Gopytext.setWidth(0);
		chuchay.setText(Gopytext.getText().toString());
		chuchay.setSelected(true);		
    	String sentence = Getdata();
    	Log.i("Duong", sentence);
		new LongOperation().execute("2", sentence);
		SetEnable(false);
    }
    private String Getdata() {
		JSONObject data = new JSONObject();
    	JSONArray array = new JSONArray();
    	
    	try {
    		array.put(picture1);
        	array.put( picture2);
        	array.put( picture3);
        	array.put( picture4);
        	array.put( picture5);
        	array.put( picture6);
        	
			data.put("i", 1);
			data.put("thucte",E1.getText().toString() );
			data.put("muctieu",F1.getText().toString() );
			data.put("xuatsac",array);
			data.put("GopY",Gopytext.getText().toString());
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return data.toString();
	}

	public void Edit_onClick(View v){
    	
    	chuchay.setVisibility(android.view.View.INVISIBLE);
    	Gopytext.setVisibility(android.view.View.VISIBLE);
    	Button bt ;
    	bt = (Button) findViewById(R.id.Summit);
    	bt.setEnabled(true);
    	SetEnable(true);
		//int res = getResources().getIdentifier("matcuoivang", "drawable", this.getPackageName());
		
		//ImageB2 = (ImageView) findViewById(R.id.ImgDudoan2);	
		
		//ImageB2.setImageResource(res);
		//ImageA2.setImageBitmap(bitmap);
    }
   
    
    private void SetEnable(boolean b) {
		
    	E1.setEnabled(b);
    	F1.setEnabled(b);
    	Button btS,btE ;
    	btS = (Button) findViewById(R.id.Summit);
    	btS.setEnabled(b);
    	btE = (Button) findViewById(R.id.Edit);
    	btE.setEnabled(!b);
	}


	// Tao Socket
    @SuppressLint("HandlerLeak")
   	class ReceivedThread extends Thread {
   		ReceivedHandler handler = new ReceivedHandler();

   		@Override
   		public void run() {
   			Message msg = new Message();
   			Bundle args = new Bundle();
   			try {
   				String retVal = receivedData();
   				msg.what = 0;
   				args.putString("V", retVal);
   				msg.setData(args);
   				handler.sendMessage(msg);
   			} catch (IOException e) {
   				msg.what = 1;
   				args.putString("V", e.getMessage());
   				msg.setData(args);
   				handler.sendMessage(msg);
   			}
   			super.run();
   		}
   	}
       
       private String receivedData() throws IOException {
   		String res = "";   		
   		byte[] buffer = new byte[MAX_UDP_DATAGRAM_LEN];
   		DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
   		udpReceiver.receive(dp);
   		res = new String(buffer, 0, dp.getLength());
   		Log.i("Duong", res );	
   		return res;
   	}
       
       @SuppressWarnings({ "deprecation", "unused" })
   	private String getLocalIpAddress() {

   		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

   		// Get WiFi status
   		WifiInfo info = wifi.getConnectionInfo();

   		return Formatter.formatIpAddress(info.getIpAddress());
   	}

       private void setUpIOStreams() throws IOException {
   		udpReceiver = new DatagramSocket(UDP_SERVER_PORT);
   		UDP_SERVER_IP = GetConfig("IpServer");
   	}
       
       @SuppressLint("HandlerLeak")
   	public class ReceivedHandler extends Handler {
   		@Override
   		public void handleMessage(Message msg) {
   			Log.i("Duong", "handleMessage");	
   			switch (msg.what) {
   			case FINISHED_RECEIVER:
   				//setText(appendText, msg.getData().get("V").toString());
   				try {   					
					JSONObject jsonObj = new JSONObject(msg.getData().get("V").toString());					
					SetValue(jsonObj);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
   				new ReceivedThread().start();
   				break;

   			case 1:
   				showMsg(msg.getData().get("V").toString());
   				new ReceivedThread().start();
   				break;
   			}
   		}

		private void SetValue(JSONObject jsonObj) {
			// TODO Auto-generated method stub
			try {
				Log.i("Duong", jsonObj.get("i").toString());				
				if(jsonObj.get("i").toString().trim().compareTo("1")==0)
				{		Log.i("Duong", jsonObj.get("r").toString()+jsonObj.get("c").toString());				
					setText(jsonObj.get("r").toString()+jsonObj.get("c").toString(), jsonObj.get("v").toString());					
				}
				else if(jsonObj.get("i").toString().trim() == "0")
				{
					SetConfig("SoGiaiDoan", jsonObj.get("v").toString());
					SetGiaiDoan(jsonObj.get("v").toString());
				}
				else
				{
					//Nhan file anh Nhan Vien
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
   	}
    public void showMsg(String msg) {
   		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
   	}
   	private String sendDataOverConnection(String sentence) throws IOException {
   		
   		
   		//Log.i("Duong", isconnect.toString() );
   		if(isconnect)
   			setUpIOStreams();
   		DatagramSocket ds = null;
   		try {
   			ds = new DatagramSocket();
   			//Log.i("Duong", "SERVER : "  + UDP_SERVER_IP  + " PORT : " + UDP_SERVER_PORT + "_ IP Client " + getLocalIpAddress());
   			InetAddress serverAddr = InetAddress.getByName(UDP_SERVER_IP);
   			DatagramPacket dp = new DatagramPacket(sentence.getBytes(),
   					sentence.length(), serverAddr, UDP_SERVER_PORT);
   			ds.send(dp);
   			//Log.i("Duong", "SERVER : "  + UDP_SERVER_IP  + " PORT : " + UDP_SERVER_PORT + sentence );
   		} catch (SocketException e) {
   			e.printStackTrace();
   		} catch (UnknownHostException e) {
   			e.printStackTrace();
   		} catch (IOException e) {
   			throw e;
   		} catch (Exception e) {
   			e.printStackTrace();
   		} finally {
   			if (ds != null)
   				ds.close();
   		}

   		sentence = ("OUT TO SERVER: " + sentence);
   		return sentence;

   	}
       private class LongOperation extends AsyncTask<String, Void, String> {

   		@Override
   		protected String doInBackground(String... params) {
   			//Log.i("Duong", "Connet socket " +  params[0]);
   			String res = params[0];
   			if (params[0] == "1") {
   				try {
   					setUpIOStreams();
   				} catch (IOException ex) {
   					res = ex.toString();
   				}
   				// enableConnection();
   			} else if (params[0] == "2") {
   				try {
   					res = "2:" + sendDataOverConnection(params[1]);
   					Log.i("Duong", res);
   				} catch (IOException ex) {
   					res = ex.toString();
   				}

   			}
   			return res;
   		}

   		@Override
   		protected void onPostExecute(String result) {
   			//Log.i("Duong", "Connet socket");
   			if (result == "1") {
   				//Log.i("Duong", "Connet socket Start");
   				ReceivedThread th = new ReceivedThread();
   				th.start();
   				// new ReceiverOperation().execute("");
   			} else if (result.charAt(0) == '2') {
   				//setText(appendText, result.substring(2)); can sua lai
   				// new LongOperation().execute("3");
   			} else {
   				
   			}

   		}

   		@Override
   		protected void onPreExecute() {
   		}

   		@Override
   		protected void onProgressUpdate(Void... values) {
   		}

   	}
}